<template>
  <div>
    <!-- 搜索框 -->
    <el-form :inline="true" :model="queryParams" style="margin-top: 20px; margin-left: 30px;">
      <el-row>
        <el-form-item label="患者姓名">
          <el-input v-model="queryParams.userName" placeholder="请输入姓名" style="width: 120px;"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable style="width: 120px">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="queryParams.telephoneNumber" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item label="身份证号码">
          <el-input v-model="queryParams.userIdCard" placeholder="请输入身份证号码"></el-input>
        </el-form-item>
        <el-form-item label="注册起始时间">
          <el-date-picker v-model="queryParams.creatTime" type="date" placeholder="选择起始日期" value-format="yyyy-MM-dd"
            style="width: 150px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="注册截止时间">
          <el-date-picker v-model="queryParams.endTime" type="date" placeholder="选择结束日期" value-format="yyyy-MM-dd"
            style="width: 150px">
          </el-date-picker>
        </el-form-item>
      </el-row>

      <el-form-item inline>
        <el-button type="primary" @click="getList" icon="el-icon-search" size="mini">搜索</el-button>
        <el-button @click="resetHandler" icon="el-icon-refresh" size="mini">重置</el-button>
      </el-form-item>
    </el-form>

    <!--患者的表格显示  -->
    <el-table :data="tableData" v-loading="loading">
      <el-table-column width="55" align="center" />
      <el-table-column label="id" prop="userId" width="80" align="center"></el-table-column>
      <el-table-column label="患者姓名" prop="userName" width="100" align="center"></el-table-column>
      <el-table-column label="性别" prop="userGender" width="80" align="center"></el-table-column>
      <el-table-column label="年龄" prop="userAge" width="80" align="center"></el-table-column>
      <el-table-column label="手机号" prop="userPhoneNumber" width="190" align="center"></el-table-column>
      <el-table-column label="身份证号" prop="userIdCard" width="250" align="center"></el-table-column>
      <el-table-column label="注册时间" prop="userCreateTime" width="150" align="center">
        <template slot-scope="scope">
          {{ formatDate(scope.row.userCreateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="账号状态" width="180" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.userStatus" :active-value="1" :inactive-value="0" active-text="启用"
            inactive-text="禁用" active-color="#67C23A" inactive-color="#F56C6C"
            :loading="scope.row.statusLoading || false"
            @change="(val) => handleStatusChange(scope.row, val)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="记录" width="220" align="center">
        <template slot-scope="scope">
          <el-radio-group v-model="direction" style="display: none">
            <el-radio label="rtl"></el-radio>
          </el-radio-group>

          <el-button @click="openDrawer(scope.row.userId)" type="primary" style="margin-left: 16px;">
            患者记录
          </el-button>

          <el-drawer title="就诊记录" :visible.sync="drawer" :direction="direction" :before-close="handleClose" size="50%">
            <div v-if="recordLoading" style="text-align: center; padding: 20px;">
              <el-spinner />
              <p>加载中...</p>
            </div>
            <div v-else-if="medicalRecords && medicalRecords.length > 0">
              <el-table :data="medicalRecords" border>
                <el-table-column prop="medicalRecordCreateTime" label="就诊日期" width="180" />
                <el-table-column prop="patientDescription" label="病人身体状况" />
                <el-table-column prop="medicalRecord" label="诊断结果" />
                <el-table-column prop="doctorOpinion" label="医生意见" />
                <el-table-column prop="doctor.doctorName" label="主治医生" width="120" />
              </el-table>
            </div>
            <div v-else style="text-align: center; padding: 20px;">
              暂无就诊记录
            </div>
          </el-drawer>
        </template>
      </el-table-column>
      <!--相关操作 scop.row表示当前行的相关信息  -->
      <el-table-column label="操作" width="220" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button @click="deleteHandler(scope.row)" size="mini" type="text" icon="el-icon-delete">删除</el-button>
          <el-button @click="resetPassword(scope.row)" size="mini" type="text" icon="el-icon-refresh">重置密码</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
  </div>
</template>

<script>
import { listPatient, DeletePatient, ResetPatient, UpdateStatus, SelectRecord } from '@/api/patient/list.js'

export default {
  data() {
    return {
      drawer: false,  // 控制抽屉是否显示，默认隐藏
      direction: 'rtl',  // 抽屉打开方向，默认从右往左
      loading: false,
      recordLoading: false, // 就诊记录加载状态
      medicalRecords: null, // 存储就诊记录数据
      // 查询参数
      queryParams: {
        userName: '',
        gender: '',
        status: '',
        userIdCard: '',
        telephoneNumber: '',
        creatTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 10
      },
      tableData: [],
      total: 0
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 打开抽屉并获取就诊记录
    openDrawer(userId) {
      this.drawer = true
      this.recordLoading = true
      this.medicalRecords = null
      SelectRecord(userId).then(response => {
        console.log("数据：", response.rows)
        this.medicalRecords = response.rows || []
      }).catch(error => {
        console.error('获取就诊记录失败:', error)
        this.$message.error('获取就诊记录失败')
      }).finally(() => {
        this.recordLoading = false
      })
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },

    // 状态切换处理
    async handleStatusChange(row, newStatus) {
      try {
        const action = newStatus === 1 ? '启用' : '禁用'
        await this.$confirm(`确定要${action}用户 ${row.userName} 吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        this.loading = true
        const res = await UpdateStatus(row.userId)

        if (res.code === 200) {
          this.$message.success(`已成功${action}用户`)
          // 更新本地状态
          row.userStatus = newStatus
        } else {
          this.$message.error(res.msg || '操作失败')
          // 恢复原状态
          row.userStatus = newStatus === 1 ? 0 : 1
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error.message || '操作失败')
          // 恢复原状态
          row.userStatus = newStatus === 1 ? 0 : 1
        }
      } finally {
        this.loading = false
      }
    },

    //重置用户密码
    resetPassword(row) {
      this.$confirm(`确定要重置用户 ${row.userName} 的密码吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true
          const res = await ResetPatient(row.userId)
          if (res.code === 200) {
            this.$message.success('密码重置成功')
            this.getList()
          } else {
            this.$message.error(res.msg || '密码重置失败')
          }
        } catch (error) {
          this.$message.error(error.message || '密码重置失败')
        } finally {
          this.loading = false
        }
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    },

    //删除用户
    deleteHandler(row) {
      this.$confirm(`确定要删除用户 ${row.userName} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true
          const res = await DeletePatient(row.userId)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.getList()
          } else {
            this.$message.error(res.msg || '删除失败')
          }
        } catch (error) {
          this.$message.error(error.message || '删除失败')
        } finally {
          this.loading = false
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 格式化日期显示（去掉时间部分）
    formatDate(dateTimeString) {
      if (!dateTimeString) return ''
      return dateTimeString.split(' ')[0]
    },

    // 重置搜索条件
    resetHandler() {
      this.queryParams = {
        userName: '',
        gender: '',
        status: '',
        telephoneNumber: '',
        userIdCard: '',
        creatTime: '',
        endTime: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getList()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },

    // 获取列表数据
    async getList() {
      try {
        this.loading = true
        const res = await listPatient({
          userName: this.queryParams.userName,
          gender: this.queryParams.gender,
          status: this.queryParams.status,
          userIdCard: this.queryParams.userIdCard,
          telephoneNumber: this.queryParams.telephoneNumber,
          creatTime: this.queryParams.creatTime,
          endTime: this.queryParams.endTime,
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        })
        this.tableData = res.rows
        this.total = res.total
      } catch (error) {
        this.$message.error(error.message || '获取数据失败')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.el-switch {
  height: 32px;
}

.el-switch__core {
  height: 24px;
  border-radius: 12px;
}

.el-switch__label {
  color: #fff;
  font-weight: bold;
  font-size: 12px;
}

.el-switch__label.is-active {
  padding: 0 8px;
}
</style>